<template>
  <div id="manageUserPage">
    <a-form layout="inline" :model="searchParams" @finish="doSearch" style="margin-bottom: 16px">
      <a-form-item label="账号">
        <a-input v-model:value="searchParams.userAccount" allow-clear placeholder="输入账号" />
      </a-form-item>
      <a-form-item label="用户名">
        <a-input v-model:value="searchParams.userName" allow-clear placeholder="输入用户名" />
      </a-form-item>
      <a-form-item label="角色">
        <a-select
          style="width: 200px"
          v-model:value="searchParams.userRole"
          :options="userRoles"
          allow-clear
        />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit">查询</a-button>
      </a-form-item>
    </a-form>
    <a-table
      :columns="columns"
      :data-source="dataList"
      :pagination="pagination"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, text, record }">
        <div>
          <a-input
            v-if="editableData[record.id]"
            v-model:value="editableData[record.id][column.dataIndex]"
            style="margin: -5px 0"
          />
        </div>
        <template
          v-if="
            column.dataIndex === 'userAccount' ||
            column.dataIndex === 'userName' ||
            column.dataIndex === 'userProfile'
          "
        >
          <div style="width: 80px">
            {{ text }}
          </div>
        </template>
        <template v-if="column.dataIndex === 'userAvatar'">
          <a-image :src="record.userAvatar" :width="48" />
        </template>
        <template v-if="column.dataIndex === 'userRole'">
          <div v-if="record.userRole === 'admin'">
            <a-tag color="red">管理员</a-tag>
          </div>
          <div v-else>
            <a-tag color="blue">普通用户</a-tag>
          </div>
        </template>
        <template v-if="column.dataIndex === 'createTime'">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-else-if="column.key === 'action'">
          <div class="updateUserData">
            <span v-if="editableData[record.id]">
              <a-button type="primary" @click="save(record.id)">保存</a-button>
              <a-popconfirm title="确定取消?" @confirm="cancel(record.id)">
                <a-button type="primary">取消</a-button>
              </a-popconfirm>
            </span>
            <span v-else>
              <a-button type="primary" @click="edit(record.id)">编辑用户</a-button>
              <a-button type="primary" danger @click="doDelete(record.id)" style="margin-left: 10px">
                删除
              </a-button>
            </span>
          </div>
        </template>
      </template>
    </a-table>
  </div>
</template>
<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { deleteUserUsingPost, listUserVoByPageUsingPost } from '@/api/userController.ts'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { cloneDeep } from 'lodash-es'
import type { UnwrapRef } from 'vue'

const columns = [
  {
    title: '账号',
    dataIndex: 'userAccount',
  },
  {
    title: '用户名',
    dataIndex: 'userName',
  },
  {
    title: '头像',
    dataIndex: 'userAvatar',
  },
  {
    title: '简介',
    dataIndex: 'userProfile',
  },
  {
    title: '角色',
    dataIndex: 'userRole',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
  },
  {
    title: '操作',
    key: 'action',
  },
]

// 用户数据列表
const dataList = ref([])
// 用户数量
const total = ref(0)

// 搜索条件
const searchParams = reactive<API.UserQueryRequest>({
  current: 1,
  pageSize: 10,
  userAccount: '',
  userName: '',
  userRole: '',
})
// 获取数据
const fetchData = async () => {
  const res = await listUserVoByPageUsingPost({
    ...searchParams,
  })
  if (res.data.code === 0 && res.data.data) {
    dataList.value = res.data.data.records
    total.value = res.data.data.total
  } else {
    dataList.value = []
    total.value = 0
    message.error('获取数据失败，' + res.data.message)
  }
}
// 页面加载的时候请求一次
onMounted(() => {
  fetchData()
})
// 分页
const handleTableChange = (pagination: any) => {
  searchParams.current = pagination.current
  searchParams.pageSize = pagination.pageSize
  fetchData()
}
// 分页参数
const pagination = computed(() => {
  return {
    current: searchParams.current ?? 1,
    pageSize: searchParams.pageSize ?? 10,
    total: total.value,
    showSizeChanger: true,
    showTotal: (total) => `共 ${total} 条`,
  }
})
// 获取数据
const doSearch = () => {
  // 重置页码
  searchParams.current = 1
  fetchData()
}
// 获取角色下拉内容
const userRoles = [
  { label: '管理员', value: 'admin' },
  { label: '普通用户', value: 'user' },
]
// 删除用户
const doDelete = async (id: Number) => {
  var res = await deleteUserUsingPost({
    id: id,
  })
  if (res.data.code === 0 && res.data.data) {
    message.success('删除成功')
    fetchData()
  } else {
    message.error('删除失败，' + res.data.message)
  }
}

// 编辑用户
const editableData: UnwrapRef<Record<string, API.UserUpdateRequest>> = reactive({})
const dataSource = ref(dataList)
const edit = (key: string) => {
  editableData[key] = cloneDeep(dataSource.value.filter((item) => key === item.id)[0])
}
const save = (key: string) => {
  Object.assign(dataSource.value.filter((item) => key === item.id)[0], editableData[key])
  delete editableData[key]
}
const cancel = (key: string) => {
  delete editableData[key]
}
</script>

<style scoped>
.editable-row-operations a {
  margin-right: 8px;
}
</style>
